package com.itkf.common.StrategyModel;

import com.itkf.common.MyApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class StrategyChoose implements ApplicationListener<ApplicationEvent> {
    private static final Map<String, AbstractStrategy> strategyChoose = new HashMap();

    public static AbstractStrategy choose(String mark) {
        return Optional.ofNullable(strategyChoose.get(mark))
                .orElseThrow(() -> new RuntimeException("策略未定义"));
    }

    public <Request> void execute(String mark, Request request) {
          choose(mark).handle(request);
    }

    public <Request, Response> Response executeWithResponse(String mark, Request request) {
        return choose(mark).handlewithResponse(request);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        Map<String, AbstractStrategy> beanMap =
                MyApplicationContext.getBeanFromType(AbstractStrategy.class);
        beanMap.forEach((beanName, bean) -> {
            if (strategyChoose.containsKey(bean.Mark())) {
                throw new RuntimeException("重复策略");
            }
            strategyChoose.put(bean.Mark(), bean);
        });
    }
}
